define(['jquery', 'bootstrap', 'backend','frontend', 'form', 'template','highcharts'], function ($, undefined, Backend,Frontend, Form, Template,Highcharts) {
    var Controller = {
        info: function () {
            //快照  页面要求5秒刷新一次
            // Controller.datasnap();
            // setInterval(function(){
            //     Controller.datasnap();
            // }, 5000);
            //  流量分布
            Controller.flow();
            //  连接分布
            Controller.link();
            setInterval(function(){
                Controller.flow();
                Controller.link();
            }, 60000);
        },
        flow: function () {
            // console.log(456);
            // var returnv = true;
            $.ajax({
                url: '/index/flow/flow',
                type:'post',
                data: {type: 'flow'},
                dataType:'json',
                success:function(json){
                    // console.log(json.data);                    
                   Controller.piechart(json.code,json.msg,json.data, "pie", "flow");                    
                }
            });
            // return returnv;
        },
        link: function () {
            // console.log(456);
            $.ajax({
                url: '/index/flow/link',
                type:'post',
                data: {type: 'link'},
                dataType:'json',
                success:function(json){                    
                    Controller.piechart(json.code,json.msg,json.data, "pie", "connect");                    
                }
            });
        },
        piechart: function(code,msg,json, type, id){ //画图 饼图/趋势图   数据   类型  id
            if(code == 401){
                Backend.api.toastr.error(msg);
                window.location.href='/index/user/login';
                return false;
            }


            if(id == 'connect' ){
                text = '连接分布';
            }else if(id == 'flow'){
                text = '流量分布';
            }
            if(code == 0 || code == 403){
                options = {
                    positionClass: "toast-top-center",
                };
                // alert(msg);
                Backend.api.toastr.error(text+msg,'',options);
                return false;
            }

            var data = Controller.map(json, function(r) {
                return {
                    name: r.name,
                    y: Number(r.data),
                    color: r.color
                }
            });
            Highcharts.chart(id, {
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: type
                },
                title: {
                    text: text,
                    style: {
                        // color: 'red',   //字体颜色
                        fontSize:"14px", //字体大小
                        "font-weight": "bold",
                    }      
                },
                tooltip: {
                    // pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>',
                    style: {font:'normal 10px sans-serif', fontSize:'10px'},
                    formatter:function(){
                        return this.point.name+ ' '+(this.percentage).toFixed(1)+'%'+' '+Controller.numberformat(this.y);
                    }
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                            style: {
                                color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                            }
                        }
                    }
                },
                exporting: {
                    enabled: false
                },//隐藏导出
                credits: { 
                    enabled: false
                },//隐藏右下角highcharts的链接
                series: [{
                    name: 'Brands',
                    colorByPoint: true,
                    data: data
                }]
            });
        },
        numberformat: function(num){    //流量单位转换
            if (num >= 1024 * 1024 * 1024)
                return ((num / (1024 * 1024 * 1024))).toFixed(2) + 'G';
            else
            if (num >= 1024 * 1024)
                return ((num / (1024 * 1024))).toFixed(2) + 'M';
            else     
            if (num >= 1024)
                return ((num / 1024)).toFixed(2) + 'K';
            else
                return num;
        },
        map: function(array, f) {
            // array = JSON.parse(array);
            var out = [];
            for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
            return out;
        },
        datasnap: function(){//快照
            $.ajax({
                url: '/index/flow/snap',
                type:'post',
                data: {type: 'snap'},
                success:function(data){
                    // console.log(eval('('+data+')'));return false;
                    try {
                        // console.log(123);return false;
                        json = eval('('+data+')');
                        // console.log(json);return false;
                        document.getElementById("dvout").innerHTML = Controller.numberformat(json.out);
                        document.getElementById("dvin").innerHTML = Controller.numberformat(json.in);
                        document.getElementById("dvflow").innerHTML = json.flow;
                        document.getElementById("dvpps").innerHTML = json.pps;
                        document.getElementById("dvuser").innerHTML = json.user;
                        document.getElementById("dvsyn").innerHTML = json.tcpsyn_pps;
                        document.getElementById("dvsynack").innerHTML = json.tcpsynack_pps;
                        document.getElementById("dvtcp").innerHTML = json.tcpflowcnt;
                        document.getElementById("dvudp").innerHTML = json.udpflowcnt;
                        document.getElementById("dvicmp").innerHTML = json.icmpflowcnt;
                        document.getElementById("dvusermax").innerHTML = json.user_max;                        
                    }catch(e) {
                        // console.log(321);return false;
                    }
                }
            })
        },
        appgroupchart_show: function(charttype, bridge, group, hours, tmend, render)//上下行流量趋势
        {
            AJXS({
                type: 'POST',
                url: 'ajax_group_stat?type=appgroupchart&charttype='+charttype+'&bridge='+bridge+'&hours='+hours+'&tmend='+tmend+'&group='+group,
                error: function(status){},
                success: function(data) {
                    try {
                        stackchart_show(charttype, render, eval('('+data+')'));
                    }catch(e) {
                    }
                }
            })
        },
        stackchart_show: function(chartype, render, json)
        {
            Highcharts.setOptions({ global: { useUTC: false } });
            var units = 'bits/s';
            if (chartype == "flow") 
                units = "#flowcnt";
            var options = {
                chart:{
                    renderTo:render,
                    borderRadius:0,
                    defaultSeriesType:'area',
                    borderWidth: 1,
                    borderColor:'#D3DCEB',
                    borderRadius:4
                },title:{
                    text:null
                },xAxis:{
                    type:'datetime',
                    tickPixelInterval:80,
                    labels:{
                        rotation:-45,
                        align:'right',
                        style:{font:'normal 10px sans-serif', color:'#000000'}
                    }
                },yAxis:{
                    min:0,
                    tickPixelInterval:30,
                    labels:{
                        style:{font:'normal 10px sans-serif', color:'#000000'}
                    },
                    title:{ text:units },
                    plotLines:[{value:0,width:1}]
                },legend:{enabled:true, align:'right', symbolHeight:8, symbolWidth:8, symbolRadius:8, verticalAlign:'top', y:0, margin: 15, 
                    padding: 0, lineHeight:1,itemStyle:{fontSize:'10', fontWeight:'thin', color:'#aaa'}
                },plotOptions:{area:{stacking:'normal',lineWidth:0,marker:{enabled:false}}
                },credits:{enabled:false},
                tooltip:{
                    shared: true,
                    formatter: function () {
                        var s1 = '<span style="font:normal 10px sans-serif;">' + Highcharts.dateFormat("%m/%d %H:%M", this.x)+'</span>';
                        var s2 = '', s3 = '';
                        var cnt = 0;
                        $.each(this.points, function () {
                            cnt += this.y;
                            s2 += '<br/><span style="font:normal 10px sans-serif;color:#666;padding:1px 0;">'+this.series.name+': '+
                                numberformat(this.y)+'</span>';
                        });
                        s3 = '<br><span style="margin-top:3px; font-size:11px;">合计:'+numberformat(cnt)+'</span>';
                                                
                        return s1+s2+s3;
                    }
                },series:[]
            }
            for (i = 0; i < json.rows.length; i++) {
                json.rows[i].name = json.grpcname[i];
                json.rows[i].color = json.colors[i];
            }
            options.series = json.rows;
            new Highcharts.Chart(options);
        }
    };
    return Controller;
});